<?php
namespace app\base\service;

use GatewayWorker\Lib\Gateway;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

class GatewayEvents
{
    public static function onWorkerStart($businessWorker)
    {
        // 初始化Redis连接等操作
    }

    public static function onConnect($client_id)
    {
        Log::instance()->info("websocket:{$client_id}连接成功");
        echo date("Y-m-d H:i:s")."websocket:{$client_id}登录成功";
        Gateway::sendToClient($client_id, json_encode([
            'type' => 'welcome',
            'client_id' => $client_id
        ]));
    }

    public static function onMessage($client_id, $message)
    {
        //Log::instance()->info("websocket:pong->".$message);
        $data = json_decode($message, true);
        switch ($data['action'] ?? '') {
            case 'login':
                self::handleLogin($client_id, $data);
                break;
            case 'service':
                self::handleService($client_id, $data);
                break;
            case 'pong':
                Db::instance()->name('ai_device')->where(['id' => $data['device_id']])->update(['work_status' => $data['status']]);
                Log::instance()->info("websocket:pong->".$message);
                break;
        }
    }

    private static function handleLogin($client_id, $data)
    {
        $device_id = $data['device_id'] ?? '';
        if ($device_id) {
            // 绑定UID
            Gateway::bindUid($client_id, $device_id);
            Db::name('ai_device')->where(['id' => $device_id])->update(['status' => 1,'client_id'=>$client_id]);
          //  Cache::store('redis')->set("device:{$device_id}", $client_id, 3600);
            Log::instance()->info("websocket:{$device_id}登录成功");
            echo date("Y-m-d H:i:s")."websocket:{$device_id}登录成功";
            Gateway::sendToClient($client_id, json_encode([
                'action' => 'login',
                'code' => 200
            ]));
        }
    }

    private static function handleService($client_id, $data)
    {
        $target_device = $data['target_device'] ?? '';
        if ($target_device) {
            Gateway::sendToUid($target_device, json_encode([
                'action' => "notifier",
                'data' => $data['content']
            ]));
            Log::instance()->info("websocket:{$client_id}发送消息给{$target_device}");
            $r = json_encode([
                'action' => "notifier",
                'data' => $data['content']
            ]);
            Log::instance()->info("websocket:{$client_id}发送消息给{$target_device}:$r");
            echo date("Y-m-d H:i:s")."websocket:{$client_id}发送消息给{$target_device}";
        }
    }

    public static function onClose($client_id)
    {
        Db::name('ai_device')->where(['client_id' => $client_id])->update(['status' => 0]);
        Log::instance()->info("websocket:{$client_id}断开连接");
        echo date("Y-m-d H:i:s")."{$client_id}断开连接";
    }
}
